<?php
/**
 * Created by PhpStorm.
 * User: zhanghua
 * Date: 2018/9/27
 * Time: 9:10
 */

namespace app\common\service;


class ModelBaseService extends BaseService
{
    protected $modelName = '';

    public function init()
    {
        parent::init();

        if(!$this->modelName){
            throw new \Exception('The service of ' . static::class . ' miss the attribute modelName!');
        }
    }

    /**
     * 保存一条新数据或者根据主键更新一条记录
     * @param $data
     * @return bool|mixed
     */
    protected function save($data)
    {
        $Model = new $this->modelName;

        $pk = $Model->getPk();

        if(isset($data[$pk])){ //更新
            $result = $Model->allowField(true)->isUpdate(true)->save($data, [$pk => $data[$pk]]);
        }else{
            $result = $Model->allowField(true)->isUpdate(false)->save($data);//保存
        }

        return $result ? $Model->$pk : false;
    }

    /**
     * 条件更新
     * @param $data
     * @param array $where
     * @return bool
     * @throws \Exception|bool
     */
    protected function saveByWhere($data,$where=[])
    {
        if(!$where){
            throw new \Exception("where 条件不能为空");
        }

        $Model = new $this->modelName;

        $result = $Model->allowField(true)->isUpdate(true)->save($data,$where);//按where条件更新

        return $result;
    }
}